'use strict';

const Controller = require('egg').Controller;

class DoRegisterController extends Controller {
  async index() {
    const { ctx } = this;
    console.log(ctx.request.body);
    var {administrator , pwd , repwd} = ctx.request.body
    var db = this.app.mongodb
    

    var res =await db.collection("administrator").find({administrator}).toArray();

    var userReg=/^[a-zA-Z][a-zA-Z0-9]{3,15}$/;
    var pwdReg=/^[a-zA-Z0-9]{4,10}$/;    

    if (res.length) {
      ctx.body = "<script>alert('该用户名已被注册');location.href='/register'</script>"
    }else if(pwd != repwd){
      ctx.body = "<script>alert('确认密码不正确！');location.href='/register'</script>"
    }else if(userReg.test(administrator) == false) {
      ctx.body = "<script>alert('用户名只能包含数字与字母，长度在3-15之间');location.href='/register'</script>"
    }else if(pwdReg.test(pwd) == false) {
      ctx.body = "<script>alert('密码不能含有非法字符，长度在4-10之间');location.href='/register'</script>"
    }else{
      var res = await db.collection("administrator").insertOne({administrator,pwd})
      ctx.cookies.set("login","success")
      ctx.body = "<script>alert('恭喜成功注册！正在进入主页');location.href='/home'</script>"
    }
  }
}

module.exports = DoRegisterController;
